var express = require("express");
var multer = require('multer')

let fs = require('fs');
const OSS = require('ali-oss');

var router = express.Router();
var upload = multer({ dest: __dirname + '../../../tmp/' })



router.post('/', upload.single('file'), async (req, res) => {
  let path = req.file.path
  let originalname = req.file.originalname
  // 获得到上传的img_url

  let result = await putStream(path, originalname)

  // tmp\abe0540355da563663d3f1120991141e
  deleteDir(path)

  res.send({ code: 1, msg: '获取成功', url: result.url })
})

async function deleteDir(path){
  var isDelete = false
  console.log(path, 'delete path');
  const res = await fs.unlink(path, (err) => {
    if (err) throw err;
    isDelete = true
    console.log('删除成功');
  });
  return res
}


async function putStream(path, originalname) {
  console.log(originalname, 'originalname');
  const client = new OSS({
    accessKeyId: 'LTAI4G8uNgE8wHmh98en37hg',
    accessKeySecret: 'kjBv7T3tsZNdeMvV9tV7RBNA00gatF',
    bucket: 'glack',
    region: 'oss-cn-shanghai',
  });

  try {
    let stream = fs.createReadStream(path);
    // console.log(stream, 'stream');
    // console.log(originalname, 'originalname');
    var result = await client.putStream(originalname, stream);
  } catch (e) {
    console.log(e);
  }
  return result
}

module.exports = router;
